// @flow
import React from 'react'
import Sidebar from 'containers/SidebarContainer'
import { Link } from 'react-router-dom'
import { Spin, Select, Row, Col, Button, DatePicker, Icon } from 'antd'
import Moment from 'moment'
import FaultMap from 'components/FaultMap'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import styles from './FaultDistribution.css'
import { connect } from 'react-redux'
import { toggleSidebar } from 'store/modules/sidebar'
import classnames from 'classnames/bind'
const cx = classnames.bind(styles)
const Option = Select.Option
type State = {
  mapData: Array<Object>,
  count: Object,
  condition: {
    faultType: Array<string>
  },
  selectVal: Object,
  loading: boolean,
  footVisible: boolean
}
type Props = {
  userId: string,
  toggleSidebar: Function
}
let items = []  // 图例  【'事件类型1', '事件类型2', '事件类型3'】
let sym = ['rect', 'triangle', 'circle', 'roundRect', 'diamond', 'arrow', 'pin'] // 图例前面的图标
class Fault extends React.Component {
  state: State
  props: Props
  SelectMap: Function
  selectVal: Function
  hideFoot: Function
  showFoot: Function
  constructor (props: Object) {
    super(props)
    this.state = {
      loading: true,
      footVisible: false,
      mapData:[],
      count:{
        count:[],
        startDate:'',
        endDate:''
      },
      condition: {
        faultType: []
      },
      selectVal: {
        faultLimit: '',
        faultType: '',
        startDateTime: '',
        endDateTime: ''
      }
    }
    this.selectVal = this.selectVal.bind(this)
    this.SelectMap = this.SelectMap.bind(this)
    this.hideFoot = this.hideFoot.bind(this)
    this.showFoot = this.showFoot.bind(this)
  }
  componentDidMount () {
    this.draw(this.props)
  }

  hideFoot () {
    this.setState({
      footVisible: false
    })
  }

  showFoot () {
    this.setState({
      footVisible: true
    })
  }
  componentWillMount () {
    const component = this
    // 左下角客户
    universalFetch(`${__SERVICE_API__}device/events1/faults/count?userId=${this.props.userId}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        component.setState({
          count:{
            count:[result.count, result.typeCount],
            startDate:result.startTime,
            endDate:result.endTime
          }
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
      // 查询条件
    universalFetch(`${__SERVICE_API__}device/events1/faults/types?userId=${this.props.userId}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        items = result.map((d, i) => {
          return d
        })
        component.setState({
          condition:{
            faultType:result
          }
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  draw (props) {
    const component = this
    const { selectVal } = this.state
    const colors = ['#fd0511', '#fd05e3', '#a305fd',
      '#4b05fd', '#0585fd', '#05fdee', '#05fd80',
      '#9dfd05', '#fdf405', '#fd8505', '#fd8505'
    ]
    const { userId } = props
    // 地图
    universalFetch(`${__SERVICE_API__}device/customers/faults?userId=${userId}&faultLimit=${selectVal.faultLimit}` +
      `&faultType=${selectVal.faultType}` +
      `&startDateTime=${selectVal.startDateTime}` +
      `&endDateTime=${selectVal.endDateTime}`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      const sourseData = []
      let len = sym.length
      items.map((item, i) => {
        let n = i % len
        let n2 = i % colors.length
        sourseData.push({
          name: item,
          type: 'scatter',
          coordinateSystem: 'bmap',
          symbol: sym[n],
          symbolSize: 16,
          // symbolSize: function (val) {
          //   if (val) {
          //     return val[2] * 10
          //   }
          // },
          itemStyle:{
            normal: {
              borderColor: '#000',
              borderWidth: 0.5,
              borderType: 'solid',
              color: colors[n2]
            }
          },
          data: json.result.map((data, index) => {
            if (data.faults[item]) {
              data['value'] = [data.region.longitude, data.region.latitude, data.faults[item]]
              return data
            }
          }).filter((dd) => dd)
        })
      })
      component.setState({
        loading: false,
        mapData: sourseData
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  selectVal (key: string, value: string) {
    // selectVal = Object.assign({}, selectVal, {
    //   [key]: value
    // })
    this.setState({
      selectVal: Object.assign({}, this.state.selectVal, {
        [key]: value
      })
    })
  }
  SelectMap () {
    this.draw(this.props)
  }
  render () {
    const { count, condition, footVisible, selectVal } = this.state
    const component = this
    const footleft = ['故障数量', '故障类型']
    // const symbol = ['symbol/fault1.png', 'symbol/fault2.png', 'symbol/fault3.png']
    const { toggleSidebar } = this.props
    const footIconStyle = cx({
      'footCon-icon': true,
      'down': footVisible,
      'up': !footVisible
    })
    const footConStyle = cx({
      'footCon': true,
      'footCon-show': footVisible,
      'footCon-hidden': !footVisible
    })
    return (
      <div className={styles['home']}>
        <Sidebar id='fault' type='pin' title='查询条件'>
          <div className={styles['sideGroup']}>
            <Row>
              <Col span={8}>故障排名</Col>
              <Col span={14}>
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} size='small' value={selectVal.faultLimit} style={{ width:125, color:'#999' }}
                  onChange={function (value) { component.selectVal('faultLimit', value) }}>
                  <Option value=''>全部</Option>
                  <Option value='5'>前5条</Option>
                  <Option value='10'>前10条</Option>
                </Select>
              </Col>
            </Row>
            <Row>
              <Col span={8}>选择故障</Col>
              <Col span={14}>
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} size='small' value={selectVal.faultType} style={{ width:125, color:'#999' }}
                  onChange={function (value) { component.selectVal('faultType', value) }}>
                  <Option value=''>全部</Option>
                  {
                    condition.faultType.map((data, i) => {
                      return <Option key={i} value={data}>{data}</Option>
                    })
                  }
                </Select>
              </Col>
            </Row>
            <Row>
              <Col span={8}>时间范围</Col>
              <Col span={14}>
                <DatePicker size='small'
                  style={{ width:125, marginBottom:10, color:'#999' }} placeholder='开始时间'
                  onChange={function (value) { component.selectVal('startDateTime', value) }} />
              </Col>
            </Row>
            <Row>
              <Col span={8} />
              <Col span={14}>
                <DatePicker size='small'
                  style={{ width:125, marginBottom:10, color:'#999' }} placeholder='结束时间'
                  onChange={function (value) { component.selectVal('endDateTime', value) }} />
              </Col>
            </Row>
          </div>
          <p className={styles['slideFoot']}>
            <Button size='small' style={{ marginRight:5 }} onClick={() => toggleSidebar('fault')}>取消</Button>
            <Button size='small' type='primary' onClick={this.SelectMap} >确定</Button>
          </p>
        </Sidebar>
        <Spin className={styles['spin']} spinning={this.state.loading} />
        <FaultMap data={this.state.mapData} />
        <div className={styles['homeTop']}>
          <ul className={styles['homeTab']}>
            <Link to='/'>
              <li>客户分布</li>
            </Link>
            <Link to='/fault-distribution'>
              <li className={styles['act']}>故障分布</li>
            </Link>
          </ul><br />
        </div>
        {
          !footVisible
          ? <Icon type='up' className={footIconStyle} onClick={this.showFoot} id='footCon-up' />
          : false
        }
        <div className={footConStyle}>
          {
            footVisible
            ? <Icon type='down' className={footIconStyle} onClick={this.hideFoot} />
            : false
          }
          <div className={styles['footConLeft']}>
            {
              count.count.map((data, i) => {
                return <ul key={i} className={styles['footList']}>
                  <li className={styles['act']}><span>{footleft[i]}</span></li>
                  <li style={{ marginLeft:2, width:96 }}> <span>{data}</span></li>
                </ul>
              })
            }
            <br />
            <ul className={styles['footList']}>
              <li className={styles['act']}><span>时间范围</span></li>
              <li style={{ marginLeft:2, width:296 }}>
                <span style={{ paddingRight:10 }}>
                  { count.startDate
                    ? Moment(count.startDate, 'YYYY-MM-DDThh:mm:ssSSSZ').format('YYYY-MM-DD hh:mm:ss') : ''}
                </span>至
                <span style={{ paddingLeft:10 }}>
                  { count.endDate
                    ? Moment(count.endDate, 'YYYY-MM-DDThh:mm:ssSSSZ').format('YYYY-MM-DD hh:mm:ss') : ''}
                </span>
              </li>
            </ul>
          </div>
          <div className={styles['splitbg']} />
          <div className={styles['footConRight']}>
            <ul>
              <li className={styles['footTipli']}>
                {
                  // condition.faultType.map((data, i) => {
                  //   let len = symbol.length
                  //   let n = i % len
                  //   return <p key={i}><img src={symbol[n]} />{data}</p>
                  // })
                }
              </li>
            </ul>
          </div>
        </div>
      </div>
    )
  }
}

const mapStateToProps = state => {
  return {
    userId: state.user.userId
  }
}
const mapDispatchToProps = {
  toggleSidebar
}
export default connect(mapStateToProps, mapDispatchToProps)(Fault)
